package question;

import java.util.concurrent.CountDownLatch;

/**
 * @program: javase
 * @description: 使用 CountDownLatch
 * @author: lld
 * @create: 2021-04-01 19:54
 **/
public class Question2 {
    private int n = 1;//标志位

    public synchronized void printOdd(int num) throws InterruptedException {
//        判断等待
        if (n == 0) wait();
        if (num % 2 == 1) {
            System.out.println(Thread.currentThread().getName() + ": " + num);

        }
//        唤醒
        n = 0;
        notify();
    }

    public synchronized void printEven(int num) throws InterruptedException {
//        判断等待
        if (n == 1) wait();
        if (num % 2 == 0) {
            System.out.println(Thread.currentThread().getName() + ": " + num);

        }
//        唤醒
        n = 1;
        notify();
    }
    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(3);
        Thread thread1=new Thread(()->{
            for (int i = 1; i < 11; i++) {
                System.out.println("线程1："+i);
            }
            //执行完后计数器-1
            latch.countDown();
        });
        Thread thread2=new Thread(()->{
            for (int i = 11; i < 21; i++) {
                System.out.println("线程2："+i);
            }
            //执行完后计数器-1
            latch.countDown();
        });
        Thread thread3=new Thread(()->{
            for (int i = 21; i < 31; i++) {
                System.out.println("线程3："+i);
            }
            //执行完后计数器-1
            latch.countDown();
        });
        //要求三个子线程执行完之后再执行主线程
        System.out.println("main线程开始执行");
        thread1.start();
        thread2.start();
        thread3.start();

        try {
            //main线程等待直到计数器=0
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("main线程执行完成");
    }
}
